package f.h.dragon.patterns.gateway;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Gateway: a simple Gateway, The SQL would be created in the Gateway
 * subclasses. A gateway encapsulates the semantic gap between the
 * object-oriented domain layer and the relation-oriented persistence layer.
 * More specifically, it encapsulates and centralizes the application's SQL(eg.
 * Gateway-uml1.jpg). More generally, a gateway can be anything that hides
 * access to a remote server or a complex library. For each persistent class in
 * the domain layer we assume there is a corresponding table (virtual or base)
 * in the database and we introduce a corresponding gateway(eg.
 * Gateway-uml2.jpg). Here's an object diagram showing the table schemas(eg.
 * Gateway-uml3.jpg).
 * 
 * @author Wenlong Meng(wenlong.meng@gmail.com)
 * @version 1.0 at 2012/04/23
 * @since 1.0
 */
public class Gateway {

	// local variables
	protected String driver;
	protected String dbms;
	protected String dbase;
	protected String dbaseName;

	protected String user;
	protected String password;

	protected Connection connection;
	protected Statement statement;

	// Constructor
	/**
	 * Construct a Gateway
	 * 
	 * @param driver
	 * @param dbms
	 * @param dbase
	 * @param user
	 * @param pswd
	 */
	public Gateway(String driver, String dbms, String dbase, String user,
			String pswd) {
		this.driver = driver;
		this.dbms = dbms;
		this.dbase = dbase;
		this.user = user;
		this.password = pswd;
		this.dbaseName = dbms + "/" + dbase;
		try {
			Class.forName(driver);
			connection = DriverManager.getConnection(dbaseName, user, password);
			statement = connection.createStatement();
		} catch (Exception e) {
			System.err.println("can't connect to " + dbaseName + " because "
					+ e);
			try {
				connection = DriverManager.getConnection(dbaseName
						+ ";create=true");
				statement = connection.createStatement();
			} catch (Exception e2) {
				System.err.println("can't create " + dbaseName + " because "
						+ e2);
			}
		}
	}

	// Logic
	/**
	 * release resources
	 */
	public void finalize() throws SQLException {
		statement.close();
		connection.close();
	}

	/**
	 * exec sql
	 * 
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public ResultSet execute(String sql) throws SQLException {
		ResultSet result = null;
		if (statement.execute(sql)) {
			result = statement.getResultSet();
		}
		return result;
	}

}
